package com.huawei.aiosproj.view;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.huawei.aiosproj.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;

public class SplashActivity extends AppCompatActivity {
    private Button agentBtn;
    private Button actionStart;
    private final static String TAG = SplashActivity.class.getSimpleName();

    private static final String FILE_PATH = "/data/local/tmp/input.txt";
    private static final String FILE_CONTENT = "请帮我查询陆家嘴地铁站附近的西餐厅。";

    private static final String DATA_JSON_FILE_NAME = "data.json";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN
        );
        setContentView(R.layout.activity_splash);
        // chenfuduo mark, release version should open
//         checkAndDeleteDataJson();

        agentBtn = findViewById(R.id.buttonTop);

        actionStart = findViewById(R.id.actionStart);
        actionStart.setOnClickListener(v -> {
            Toast.makeText(SplashActivity.this, "Agent 任务启动完成", Toast.LENGTH_SHORT).show();
            createAndWriteFile();
            Intent intent = new Intent(SplashActivity.this, CardActivity.class);
            startActivity(intent);
        });
    }

    /**
     * 检查当前应用沙箱中是否存在 data.json 文件，如果存在则删除。
     */
    private void checkAndDeleteDataJson() {
        // 获取应用内部存储的 files 目录
        File dir = getDir("models", Context.MODE_PRIVATE);
        String path = dir.getAbsolutePath() + File.separator;
        File dataJsonFile = new File(path + "data.json");

        if (dataJsonFile.exists()) {
            if (dataJsonFile.delete()) {
                Log.d(TAG, DATA_JSON_FILE_NAME + " deleted successfully from: " + dataJsonFile.getAbsolutePath());
                Toast.makeText(this, DATA_JSON_FILE_NAME + " deleted.", Toast.LENGTH_SHORT).show();
            } else {
                Log.e(TAG, "Failed to delete " + DATA_JSON_FILE_NAME + " from: " + dataJsonFile.getAbsolutePath());
                Toast.makeText(this, "Failed to delete " + DATA_JSON_FILE_NAME, Toast.LENGTH_SHORT).show();
            }
        } else {
            Log.d(TAG, DATA_JSON_FILE_NAME + " does not exist in: " + dataJsonFile.getAbsolutePath());
        }
    }

    private void createAndWriteFile() {

        Toast.makeText(SplashActivity.this, "开始传递任务到Agent", Toast.LENGTH_SHORT).show();

        File dir = getDir("models", Context.MODE_PRIVATE);
        String path = dir.getAbsolutePath() + File.separator;
        File file = new File(path + "input.txt");
        FileOutputStream fos = null;
        OutputStreamWriter osw = null;

        try {
            // 尝试创建父目录 (如果不存在且有权限)
            File parentDir = file.getParentFile();
            if (parentDir != null && !parentDir.exists()) {
                if (parentDir.mkdirs()) {
                    Log.d(TAG, "Parent directories created: " + parentDir.getAbsolutePath());
                } else {
                    Log.e(TAG, "Failed to create parent directories: " + parentDir.getAbsolutePath());
                    // 如果父目录创建失败，很可能写入也会失败
                }
            }

            fos = new FileOutputStream(file);
            osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8);
            osw.write(FILE_CONTENT);
            osw.flush(); // 确保内容写入文件
            Log.d(TAG, "File written successfully to: " + path);
        } catch (IOException e) {
            Log.e(TAG, "Error writing to file: " + path, e);
            // 这里可以处理异常，例如显示一个 Toast 提示用户
            // Toast.makeText(this, "Failed to write file: " + e.getMessage(), Toast.LENGTH_LONG).show();
        } finally {
            try {
                if (osw != null) {
                    osw.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                Log.e(TAG, "Error closing streams", e);
            }
        }
    }
}